
package atom.core2.j2ee.util;


import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.omg.CORBA.portable.ApplicationException;

import atom.core0.exception.BizSysException;
import atom.core1.object.PrintUtil;


/**
 * <p>Title: 一些常用的WEB工具类</p>
 * <p>Description:只能使用它的静态方法</p>
 * <p>Copyright: Copyright (c) 2004</p>
 * @author 郭兵
 * @version 1.0
 */
public class WebUtils {
	/**
	 * Log4J Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(WebUtils.class);

	/**
	 * 
	 */
	private WebUtils() {}
	

	/**
	 * 从请求对象填值到entity中
	 * @param request
	 * @param entity
	 * @throws ApplicationException
	 */
	public static void copyRequestToEntity(HttpServletRequest request, Object entity) throws BizSysException
	{
		try {
				Map map = WebUtils.getParamMapFromRequest(request);
				if (logger.isDebugEnabled()) {
					logger.debug("Reuqest的Parameter的值是：\n"
							+ map.toString());
				BeanUtils.copyProperties(entity, map);
			}
			if (logger.isDebugEnabled()) {
				logger.debug("填值后的实体" + entity.getClass().getName() + "的值是：\n"
						+ PrintUtil.getPrintString(entity));
			}
		} catch (Exception e) {
			logger.error("从request往实体填值时发生未知异常，" + e);
			throw new BizSysException(e.getMessage());
		}
	}
	
	
	/**
	 * 根据request组装GET模式下的URL字符串，比如用于产生分页链接URL
	 * @param request
	 * @return
	 */
	public static String generateSearchURL(HttpServletRequest request)
	{
		StringBuffer url = new StringBuffer();
		url.append(request.getRequestURI() + "?");
		Map map = request.getParameterMap();
		for (Iterator bIter = map.keySet().iterator(); bIter.hasNext();) {
			String key = (String)bIter.next();
			String value = request.getParameter(key);
			if (key.equalsIgnoreCase("pager.offset") || null == value)
			{
				continue;
			}
			else
			{
				try {
					url.append(key + "=" + URLEncoder.encode(value, "utf-8") + "&");
				} catch (UnsupportedEncodingException e) {
				}
			}
		}
		url.deleteCharAt(url.length()-1);

		return url.toString();
	}

	/**
	 * 根据request组装GET模式下的URL字符串，包含所有参数信息
	 * @param request
	 * @return
	 */
	public static String generateURL(HttpServletRequest request)
	{
		StringBuffer url = new StringBuffer();
		url.append(request.getRequestURI() + "?");
		Map map = request.getParameterMap();
		for (Iterator bIter = map.keySet().iterator(); bIter.hasNext();) {
			String key = (String)bIter.next();
			String value = request.getParameter(key);
			try {
				url.append(key + "=" + URLEncoder.encode(value, "utf-8") + "&");
			} catch (UnsupportedEncodingException e) {
				url.append(key + "=" + URLEncoder.encode(value) + "&");
			}
		}
		url.deleteCharAt(url.length()-1);

		if (logger.isDebugEnabled()) {
			logger.debug("根据request得到的URL为" + url.toString());
		}

		return url.toString();
	}
	
	/**
	 * 根据Request获取参数Map
	 * @param request
	 * @return
	 */
	public static Map getParamMapFromRequest(HttpServletRequest request)
	{
		Map retMap = new HashMap();
		Map map = request.getParameterMap();
		for (Iterator bIter = map.keySet().iterator(); bIter.hasNext();) {
			String key = (String)bIter.next();
			String value = request.getParameter(key);
			if (key.equalsIgnoreCase("pager.offset") || null == value)
			{
				continue;
			}
			else
			{
				retMap.put(key, value);
			}
		}

		return retMap;
	}
	



    /**  
     * 从request中获取值填充bean对象  
     *  
     * @param objClass bean的类  
     * @param request 请求对象  
     * @return object对象  
     */  
    public static Object fillBean(HttpServletRequest request,Class objClass) {   
        Object objInstance = null;   
        try {   
            objInstance = objClass.newInstance();   
        } catch (InstantiationException e1) {   
        	logger.error(e1.getMessage(), e1);    
        } catch (IllegalAccessException e1) {   
        	logger.error(e1.getMessage(), e1);    
        }   
  
        Field field;   
        String fieldName;   
        String fieldValue = "";   
        int len;   
        len = objClass.getDeclaredFields().length;   
        for (int i = 0; i < len; i++) {   
            field = objClass.getDeclaredFields()[i];   
            fieldName = field.getName();   
  
            try {   
                fieldValue = request.getParameter(fieldName);   
            } catch (Exception e1) {   
            	logger.error(e1.getMessage(), e1);    
            }   
  
            if (fieldValue != null) {   
                try {   
                    setFieldValue(field, objInstance, fieldValue);   
                } catch (IllegalAccessException e) {   
                	logger.error(e.getMessage(), e);      
                }   
            }   
        }   
        objClass = objClass.getSuperclass();   
        return objInstance;   
    }   
  
    /**  
     * 将数据赋值给指定对象的相应属性  
     *  
     * @param field 字段  
     * @param objInstance 指定对象  
     * @param value 数据  
     * @throws IllegalAccessException  
     */  
    private static void setFieldValue(Field field, Object objInstance, String value) throws IllegalAccessException {   
        String fieldType = field.getType().getName();// 取字段的数据类型   
        field.setAccessible(true);   
        try {   
            if (fieldType.equals("java.lang.String")) {   
                field.set(objInstance, value);   
            } else if (fieldType.equals("java.lang.Integer") || fieldType.equals("int")) {   
                field.set(objInstance, Integer.valueOf(value));   
            } else if (fieldType.equals("java.lang.Long") || fieldType.equals("long")) {   
                field.set(objInstance, Long.valueOf(value));   
            } else if (fieldType.equals("java.lang.Float") || fieldType.equals("float")) {   
                field.set(objInstance, Float.valueOf(value));   
            } else if (fieldType.equals("java.lang.Double") || fieldType.equals("double")) {   
                field.set(objInstance, Double.valueOf(value));   
            } else if (fieldType.equals("java.math.BigDecimal")) {   
                field.set(objInstance, new BigDecimal(value));   
            } else if (fieldType.equals("java.util.Date")) {   
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");   
                formatter.setLenient(false);   
                field.set(objInstance, formatter.parse(value));   
            } else if (fieldType.equals("java.sql.Date")) {   
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");   
                formatter.setLenient(false);   
                Date date = formatter.parse(value);   
                field.set(objInstance, new java.sql.Date(date.getTime()));   
            } else if (fieldType.equals("java.lang.Boolean") || fieldType.equals("boolean")) {   
                field.set(objInstance, Boolean.valueOf(value));   
            } else if (fieldType.equals("java.lang.Byte") || fieldType.equals("byte")) {   
                field.set(objInstance, Byte.valueOf(value));   
            } else if (fieldType.equals("java.lang.Short") || fieldType.equals("short")) {   
                field.set(objInstance, Short.valueOf(value));   
            }   
        } catch (NumberFormatException ex) {   
            // field.set(objInstance, null); 当使用简单数据类型会抛出异常   
        	logger.error(ex.getMessage(), ex);    
        } catch (ParseException e) {   
        	logger.error(e.getMessage(), e);      
            field.set(objInstance, null);   
        } catch (Exception e) {   
        	logger.error(e.getMessage(), e);      
            field.set(objInstance, null);   
        }   
    }   
	

	
}
